package com.tanhua.admin.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.captcha.generator.MathGenerator;
import com.tanhua.admin.service.AdminService;
import com.tanhua.commons.utils.Constants;
import com.tanhua.model.vo.AdminVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/system/users")
public class SystemController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 获取验证码图片
     */
    @GetMapping("/verification")
    public void verification(String uuid, HttpServletResponse response) throws IOException {

        //1、使用工具类创建一个验证码图片对象
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(299, 97);
        // 验证码，图片数据流
        String code = captcha.getCode();
        //2、验证码数据存入redis中
        redisTemplate.opsForValue().set(Constants.CAP_CODE+"_"+uuid,code,
                1, TimeUnit.MINUTES);
        //3、将验证码图片数据写入到response
        captcha.write(response.getOutputStream());
    }

    /**
     * 管理员登录（获取token）：
     *      /login
     *      参数：map
     */
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody Map map) {
        Map retMap = adminService.login(map); //token
        return ResponseEntity.ok(retMap);
    }

    /**
     * 获取管理员信息
     *   返回值：AdminVo
     *   请求方式：Post  profile
     */
    @PostMapping("/profile")
    public ResponseEntity profile() {
        AdminVo vo = adminService.profile();
        return ResponseEntity.ok(vo);
    }


    public static void main(String[] args) {
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 45);

        MathGenerator generator = new MathGenerator();
        // 自定义验证码内容为四则运算方式
        captcha.setGenerator(generator);
        // 重新生成code
        captcha.createCode();

        System.out.println(captcha.getCode());

        System.out.println(generator.verify("63+97=","160"));
    }

}
